from django.shortcuts import render_to_response
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
from django.template import RequestContext
from a115 import dateutils
from urllib import urlencode

def render(request, templ, dict):
	"""
	Just a wrapper around Django's render_to_response, passing a RequestContext.
	"""
	return render_to_response(templ, dict, context_instance=RequestContext(request))

def tuplify(arr, n=2):
	"""
	Takes a list and splits it into tuples of size n.
	""" 
	return [tuple(arr[i:i+n:]) for i in range(0, len(arr), n)]

def _getForDate(request, default=None, returnRaw=False):
	"""
	This is a utility function used in views which require a date parameter to be specified in the request.  

	Looks for a GET parameter named "forDate" in the request object.  If found, parses its value with the a115.dateutils.parse_date() function to obtain a datetime.date object.  

	If returnRaw is True, returns a tuple consisting of the parsed datetime.date object and the raw "forDate" string.  Otherwise, only returns the parsed datetime.date object.  

	If the request object has no "forDate" GET parameter, returns the default date specified in "default".  If no such date was provided, looks for a 'workdate' key in the current session.  If that fails too, returns a115.dateutils.tomorrow().  
	"""
	if not default:
		try:
			default = request.session['workdate']
		except:
			default = dateutils.tomorrow()
	if request.GET.has_key("forDate"):
		forDate = str(request.GET['forDate'])
		dt = dateutils.parse_date(forDate)
		if returnRaw:
			return (dt, forDate)
		else:
			return dt
	else:
		if returnRaw:
			return (default, False)
		else: 
			return default

def _Redirect(url_name, args=[], GET=None):
	"""
	Redirects to URL by pattern name.  Pass a dictionary to GET to have it urlencoded as a get parameter for that redirect.  
	"""
	url = reverse(url_name, args=args)
	if GET:
		url = url + "?" + urlencode(GET)
	return HttpResponseRedirect(url)
